<template>
  <div class="components-container">
    <el-dialog
      :title="dialogTitle"
      :visible="dialogVisible"
      width="50%"
      append-to-body
      @close="dialogVisible=false"
    >
      <!--开发信息提示-->
      <div name="开发信息提示" v-if="isInDevMode">
        runMode: {{ runMode }}
        <hr>
        collectionForm: {{ collectionForm }}
        <hr>
        project-id: {{ projectId }}
      </div>
      <!--form表单-->
      <el-form ref="collectionForm" :model="collectionForm" :rules="addOrUpdateFormRules" label-width="80px"
               :inline="true">
        <el-form-item label="业务类型" prop="ruleId">
          <el-select v-model="collectionForm.ruleId" placeholder="" @change="setCollectionForm($event)">
            <el-option
              v-for="item in projectTypeOptions"
              :key="item.ruleId"
              :label="item.projectTypeName"
              :value="item.ruleId">
              <span style="float: left"> {{ item.projectTypeName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px;padding-left: 5px">{{
                  item.unitPrice
                }}{{ item.currency }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="费目" prop="feeServiceName">
          <el-input v-model="collectionForm.feeServiceName"></el-input>
        </el-form-item>
        <el-form-item label="单价" prop="unitPrice">
          <el-input v-model="collectionForm.unitPrice"></el-input>
        </el-form-item>
        <el-form-item label="税率" prop="exchangeRate">
<!--          <el-input v-model="collectionForm.exchangeRate"></el-input>-->
          <el-input v-model="collectionForm.taxRate"></el-input>
        </el-form-item>
        <el-form-item label="数量" prop="workNum">
          <el-input v-model="collectionForm.workNum" @change="updateAmount" :disabled="isLadderPrice"></el-input>
        </el-form-item>
        <el-form-item label="金额" prop="amount">
          <el-input v-model="collectionForm.amount" :class="workNumOrWorkNumBChange==true?'amountEmphasize':''"></el-input>
        </el-form-item>
        <el-form-item label="币种" prop="currency">
          <el-input v-model="collectionForm.currency"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="collectionForm.remark"></el-input>
        </el-form-item>
        <el-form-item label="委托客户">
          <el-select v-model="collectionForm.customerNam" placeholder="请选择结算客户名称" >
            <el-option
              v-for="item in customerNameOptions"
              :key="item.index"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <!--弹窗的底部-->
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false;workNumOrWorkNumBChange=false;isLadderPrice=false;">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {addBillCollection, getBillCollection, updateBillCollection} from "@/api/finance/billCollection/billCollection";
import {selectConRuleByProjectId} from "@/api/contract/rules";
import {getProjectRecord} from "@/api/business/projectRecord";
import customerNameOptionsMixin from "@/mixin/tos/customerNameOptionsMixin";
import queryParamsLocalStorageMixin from '@/mixin/queryParam/queryParamsLocalStorageMixin'
import tosWorkPlaceOptionsMixin from '@/mixin/tos/tosWorkPlaceOptionsMixin'
import { shipNameOptionsMixin } from '@/mixin/tos/shipNameOptionsMixin'
import { voyageOptionsMixin } from '@/mixin/tos/voyageOptionsMixin'

export default {
  name: 'AddOrUpdateCollectionDialog',
  mixins: [queryParamsLocalStorageMixin, tosWorkPlaceOptionsMixin, customerNameOptionsMixin, shipNameOptionsMixin, voyageOptionsMixin],
  props: {
    // 在修改的时候，需要根据CollectionId 从后端获取数据
    collectionId: {
      type: String,
      default: null,
    },
    // 项目id
    projectId: {
      type: String,
      default: null,
    },
    // runMode：运行模式，如：add新增、update修改
    runMode: {
      type: String,
      default: 'add',
      validator(value) {
        return ['add', 'update'].includes(value);
      },
    },

  },
  data() {
    return {
      // 作弊码：从localStorage中获取是否处于开发模式，值为true或false
      isInDevMode: localStorage.getItem('isInDevMode') === 'true',

      tosProjectViewList: [],
      // 勾选的数据
      selectedTosProjectViews: [],
      // 弹窗是否可见
      dialogVisible: false,
      // dialog中的form
      collectionForm: {},
      // 业务类型OPTIONS
      projectTypeOptions: [],
      // 被点击的项目对象obj
      clickedProject: {},
      // dialog中的form的验证规则
      addOrUpdateFormRules: {},
      workNumOrWorkNumBChange: false,
      isLadderPrice: false,
    };
  },
  computed: {
    // dialog的标题
    dialogTitle() {
      if (this.runMode === 'add') {
        return '新增收款';
      } else if (this.runMode === 'update') {
        return '修改收款';
      }
    },
  },
  methods: {
    // 把this.form的数据提交到后端，新增收款 await addBillCollection(this.collectionForm);
    addCollection() {
      this.$modal.confirm('确认新增收款？').then(async () => {
        // 如果点击了确定按钮 提交form到后端
        await addBillCollection(this.collectionForm);
        // 关闭弹窗
        this.dialogVisible = false;
        //重置form
        this.resetForm();
        // 重新加载数据
        this.$emit('addOrUpdateSuccess', [this.projectId]);
      }).catch(() => {
      });

    },
    // 根据CollectionId 从后端获取数据
    async getCollectionById() {
      console.log('根据CollectionId 从后端获取数据');
      const response = await getBillCollection(this.collectionId);
      this.collectionForm = response.data;
      //根据费项上的项目ID拿到业务类型Options
      selectConRuleByProjectId(this.collectionForm.projectId).then(res => {
        if (res && res.code == 200) {
          this.projectTypeOptions = res.data;
        }
      });
      // 打开弹窗
      this.dialogVisible = true;
      if (this.collectionForm.workNum===null){
        this.isLadderPrice=true;
      }
    },
    // 打开弹窗
    openDialog() {
      console.log(this.runMode);
        // 当projectId不为空时，查询项目信息
        // 根据运行模式，设置form
        if (this.runMode === 'add') {
          // 如果运行模式是add，设置form为空对象
          console.log(this.projectId);
          if(this.projectId){
          this.resetForm()
          //查询项目信息
          getProjectRecord(this.projectId).then(res => {
            if (res && res.code == 200) {
              this.clickedProject = res.data;
              //查询合同信息
              selectConRuleByProjectId(this.projectId).then(res => {
                console.log(res);
                this.projectTypeOptions = res.data
                // 打开弹窗
                this.dialogVisible = true;
              });
            }
          })
          }else{
          this.$message({
            message: '请先选择项目',
            type: 'warning'
          });
        }
        } else if (this.runMode === 'update') {
          // 如果运行模式是edit，根据collectionId从后端获取数据
          this.getCollectionById();
        }

    },

    // 提交form
    submitForm() {
      this.$refs["collectionForm"].validate(valid => {
        if (valid) {
          // 如果验证通过
          if (this.runMode === 'add') {
            // 如果运行模式是add，调用新增接口
            // 赋值projectId
            this.collectionForm.projectId = this.projectId;
            this.collectionForm.gkey = this.clickedProject.gkey
            this.collectionForm.conId = this.clickedProject.conId
            this.collectionForm.customerCod = this.clickedProject.customerCod
            //this.collectionForm.customerNam = this.clickedProject.customerNam
           // this.collectionForm.customerNam=this.queryParams.customerNam

            //console.log(this.queryParams.customerNam)
            // 调用新增接口
            this.addCollection();
          } else if (this.runMode === 'update') {
            // 如果运行模式是edit，调用修改接口
            this.collectionForm.collectionSource = 3;
            this.updateCollection();
          }
        } else {
          // 如果验证不通过
          this.$modal.warning({
            title: '提示',
            content: '请检查表单是否填写正确',
          });
        }
      });
    },
    // 把this.form的数据提交到后端，修改收款 await updateBillCollection(this.collectionForm);
    updateCollection() {
      this.$modal.confirm('确认修改收款？').then(async () => {
        // 如果点击了确定按钮 提交form到后端
        await updateBillCollection(this.collectionForm);
        // 关闭弹窗
        this.dialogVisible = false;
        this.workNumOrWorkNumBChange=false
        this.isLadderPrice=false
        // 重新加载数据
        this.$emit('addOrUpdateSuccess', [this.projectId]);

       // console.log(this.collectionForm.customerNam)
      }).catch(() => {
      });
    },

    // 选择业务类型，给collectionForm赋值
    setCollectionForm(id) {
      // 根据id从this.projectTypeOptions中找到对应的对象，然后把对象的属性赋值给this.collectionForm
      let {
        projectFeeName,
        taxRate,
        unitPrice,
        currency,
        projectId
      } = this.projectTypeOptions.find(item => item.ruleId === id) || {};
      console.log(projectFeeName, taxRate, unitPrice, currency, projectId);
      console.log(this.projectTypeOptions);
      // 给this.collectionForm赋值,通过this.$set()方法，否则vue无法监听到属性的变化
      this.$set(this.collectionForm, 'feeServiceName', projectFeeName);
      this.$set(this.collectionForm, 'taxRate', taxRate);
      this.$set(this.collectionForm, 'unitPrice', unitPrice);
      this.$set(this.collectionForm, 'currency', currency);
      this.$set(this.collectionForm, 'feeServiceId', projectId);
    },

    // 重置form
    resetForm() {
      this.collectionForm = {};
    },
    
    updateAmount(){
      console.log("数量的数值变化了!")
      if (this.collectionForm.workNum!==null&&this.collectionForm.workNumB!==null&&this.collectionForm.unitPrice!==null){
        var newAmount=this.collectionForm.unitPrice*this.collectionForm.workNum*this.collectionForm.workNumB
        if (Math.floor(newAmount)===newAmount){
          this.collectionForm.amount=newAmount
        }else{
          this.collectionForm.amount=newAmount.toFixed(2)
        }
        this.workNumOrWorkNumBChange=true
        this.$message.success("金额已自动重新计算！");
      }
    },

  },
};
</script>

<style scoped>
.amountEmphasize{
  .el-input__inner{
    color: #ff0000;
  }
}

</style>
